package com.bcsp.xml.ex2;

import com.bcsp.xml.Test6;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class TestCar {

    @Test
    public void Test() throws Exception {
        //使用dom4j
        //获取文件路径
        String path = Test6.class.getClassLoader().getResource("beans.xml").getPath();
        //准备SAXReader
        SAXReader reader = new SAXReader();
        //读取文档
        Document document = reader.read(new File(path));
        Element root = document.getRootElement();
        for(Element bean : root.elements("bean")){
            String classname = bean.attributeValue("class");
            Class clz = Class.forName(classname);
            Object obj = clz.newInstance();

            //读取当前类所有的属性
            for(Field field : clz.getDeclaredFields()){
                field.setAccessible(true);
                String fieldName = field.getName();
                String fieldValue = bean.elementText(fieldName);
                //System.out.println(fieldName+":"+fieldValue);
                //属性设置内容
                field.set(obj,fieldValue);
            }
            System.out.println(obj);
        }
    }
}
